package com.asktgapp.user.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.asktgapp.JGTool.EmojiFilter;
import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.application.MyApplication;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.model.CommentVO;
import com.asktgapp.model.IndustryInfoDetailVO;
import com.asktgapp.modulebase.common.adapter.BaseAdapter;
import com.asktgapp.modulebase.common.adapter.BaseViewHolder;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.user.activity.IndustryCommentActivity;
import com.asktgapp.user.activity.ShareActivity;
import com.asktgapp.utils.ImageDisplayUtil;
import com.asktgapp.widget.RefreshRecyclerView;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018/2/24
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description: 已修改
 */

public class IndustryInfoDetailFragment extends BaseFragment {
    @InjectView(R.id.myToolbarName)
    TextView myToolbarName;
    @InjectView(R.id.addTime)
    TextView addTime;
    @InjectView(R.id.myToolbarRight)
    TextView myToolbarRight;
    @InjectView(R.id.tvShare)
    ImageView tvShare;
    @InjectView(R.id.userHead)
    ImageView userHead;
    @InjectView(R.id.ivCollect)
    ImageView ivCollect;
    @InjectView(R.id.commit)
    TextView commit;
    @InjectView(R.id.etComment)
    EditText etComment;
    @InjectView(R.id.toUserName)
    TextView toUserName;
    @InjectView(R.id.myBack)
    TextView myBack;
    @InjectView(R.id.recycle)
    RefreshRecyclerView mRefreshRecyclerView;

    @InjectView(R.id.llUserHead)
    LinearLayout llUserHead;
    private RecyclerView mRecyclerView;
    private BaseAdapter mBaseAdapter;

    private String infoId, toUserId, answerId, authorId;
    private int mPage = 1;
    private boolean isCollect = false, like;
    private int scrollY = 0, scrollToY = 160;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup
            container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_industry_info_detail, container, false);
        ButterKnife.inject(this, viewGroup);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {
        getBaseActivity().getToolbar().setVisibility(View.GONE);
//        setHasOptionsMenu(true);
        llUserHead.setVisibility(View.GONE);
        etComment.setFilters(new InputFilter[]{new EmojiFilter()});
        myBack.setOnClickListener(this);
        commit.setOnClickListener(this);
        tvShare.setOnClickListener(this);
        myToolbarRight.setOnClickListener(this);
        ivCollect.setOnClickListener(this);

        infoId = getActivity().getIntent().getStringExtra("id");

        etComment.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    commit.setVisibility(View.VISIBLE);
                } else {
                    commit.setVisibility(View.GONE);
                }
            }
        });

        mRefreshRecyclerView.setRefreshAction(new RefreshRecyclerView.Action() {
            @Override
            public void onAction(int page) {
                mPage = page;
                getRemarkList(mPage);
            }
        });
        mRefreshRecyclerView.setLoadMoreAction(new RefreshRecyclerView.Action() {
            @Override
            public void onAction(int page) {
                mPage = page;
                getRemarkList(mPage);
            }
        });
        mRecyclerView = mRefreshRecyclerView.getRecyclerView();

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                scrollY += dy;
                if (recyclerView.getLayoutManager().getChildAt(0).getRootView().findViewById(R.id.llHead0) != null)
                    scrollToY = recyclerView.getLayoutManager().getChildAt(0).getRootView().findViewById(R.id.llHead0).getHeight();

                if (scrollY >= scrollToY) {
                    llUserHead.setVisibility(View.VISIBLE);
                } else {
                    llUserHead.setVisibility(View.INVISIBLE);
                }
            }
        });

        mBaseAdapter = new BaseAdapter(getActivity()) {
            @Override
            public BaseViewHolder getViewHolder(final ViewGroup parent, int viewType) {
                BaseViewHolder holder;
                if (viewType == 1) {
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_industry_head, parent, false), new BaseViewHolder.Callbacks() {
                        @Override
                        public void bind(final BaseViewHolder holder, Object data) {
                            WebView mWebView = holder.getView(R.id.webView);
                            ImageView userHead = holder.getView(R.id.userHead);
                            final ImageView ivZan = holder.getView(R.id.ivZan);
                            final TextView tvZan = holder.getView(R.id.tvZan);
                            if (!Util.isEmpty(mIndustrDetail.getInformationDetail().getUserPic()))
                                ImageDisplayUtil.loadCircleHeadImage(getActivity(), userHead, mIndustrDetail.getInformationDetail().getUserPic());
                            holder.setText(R.id.tv_title, mIndustrDetail.getInformationDetail().getTitle());
                            Date date = Util.StrToDate(mIndustrDetail.getInformationDetail().getAddTime(), "yyyy.MM.dd HH:mm:ss");
                            String timeStr = Utils.getAskTime(date);
                            holder.setText(R.id.addTime, timeStr);
                            holder.setText(R.id.myToolbarName, mIndustrDetail.getInformationDetail().getUserName());
                            holder.setText(R.id.tv_view_number, String.valueOf(mIndustrDetail.getInformationDetail().getViewNum()));
                            holder.setText(R.id.tv_info_time,mIndustrDetail.getInformationDetail().getTalkNum() + "");
                            if (isFollow)
                                holder.setText(R.id.myToolbarRight, "已关注");
                            else
                                holder.setText(R.id.myToolbarRight, "关注");
                            if (mBaseAdapter.getItemCount() > 1) {
                                holder.getView(R.id.llNoData).setVisibility(View.GONE);
                            }

                            holder.getView(R.id.myToolbarRight).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (isFollow) {// // 0取消关注 1关注
                                        doFollow(0);
                                    } else {
                                        doFollow(1);
                                    }
                                }
                            });
                            if (like)
                                ivZan.setImageResource(R.mipmap.zan_1);
                            else
                                ivZan.setImageResource(R.mipmap.zan_2);
                            holder.setText(R.id.tvZan, String.valueOf(mIndustrDetail.getInformationDetail().getLikeNum()));
                            holder.getView(R.id.llZan).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (checkIsLogin("登录后可体验更多内容")) {
                                        int zanNumber = Integer.valueOf(tvZan.getText().toString());
                                        if (like) {
                                            like = false;
                                            dealZan(infoId, "0", 0);
                                            ivZan.setImageResource(R.mipmap.zan_2);
                                            zanNumber--;
                                        } else {
                                            like = true;
                                            dealZan(infoId, "1", 0);
                                            ivZan.setImageResource(R.mipmap.zan_1);
                                            zanNumber++;
                                        }
                                        holder.setText(R.id.tvZan, String.valueOf(zanNumber));
                                    }
                                }
                            });
                            if (!Util.isEmpty(mIndustrDetail.getInformationDetail().getContent())) {
                                WebSettings websetting = mWebView.getSettings();
                                websetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//自适应屏幕
                                websetting.setJavaScriptEnabled(true);
                                websetting.setSupportZoom(false);    // 设置可以支持缩放
                                websetting.setBuiltInZoomControls(false);        // 设置出现缩放工具
                                websetting.setAllowFileAccess(true);
                                websetting.setLoadWithOverviewMode(true);
                                websetting.setDefaultTextEncodingName("utf-8"); //设置文本编码
                                websetting.setAppCacheEnabled(true);
                                websetting.setCacheMode(WebSettings.LOAD_DEFAULT);//设置缓存模式
                                mWebView.setWebViewClient(new WebViewClient() {
                                    @Override
                                    public boolean shouldOverrideUrlLoading(WebView view, String url) {
                                        view.loadUrl(url);
                                        return super.shouldOverrideUrlLoading(view, url);
                                    }
                                });
                                mWebView.setWebChromeClient(new WebChromeClient() {
                                    @Override
                                    public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                                        result.confirm();
                                        return true;
                                    }
                                });
                                mWebView.loadDataWithBaseURL(null, mIndustrDetail.getInformationDetail().getContent(),
                                        "text/html", "utf-8", null);
                            }
                        }

                        @Override
                        public void onItemClick(View view, int position) {

                        }
                    });

                } else {
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_free_ask_hot, parent, false), new BaseViewHolder.Callbacks() {
                        @Override
                        public void bind(BaseViewHolder holder, Object data) {

                            LinearLayout allAnswer = holder.getView(R.id.llAnswerComment);
                            ImageView ivZan = holder.getView(R.id.ivZan);
                            ImageView ivAskHead = holder.getView(R.id.iv_head_ask);
                            if (data instanceof IndustryInfoDetailVO.InformationCommentListBean) {
                                final IndustryInfoDetailVO.InformationCommentListBean bean = (IndustryInfoDetailVO.InformationCommentListBean) data;
                                allAnswer.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        if (checkIsLogin("登录后可查看更多内容")) {
                                            Intent intent = new Intent(getActivity(), IndustryCommentActivity.class);
                                            intent.putExtra("id", bean.getId());
                                            intent.putExtra("comment", bean);
                                            getActivity().startActivity(intent);
                                        }
                                    }
                                });
                                ImageDisplayUtil.loadCircleHeadImage(getActivity(), ivAskHead, bean.getUserPic1());
                                Date date = Util.StrToDate(bean.getAddTime(), "yyyy.MM.dd HH:mm:ss");
                                String timeStr = Utils.getAskTime(date);
                                holder.setText(R.id.addTime, timeStr);
                                holder.setText(R.id.tv_answer, bean.getContent());
                                holder.setText(R.id.tvAskName, bean.getUsername1());
                                holder.setText(R.id.tvZan, String.valueOf(bean.getLikeNum()));

                                if (TextUtils.isEmpty(bean.getLikeId()))
                                    ivZan.setImageResource(R.mipmap.zan_2);
                                else {
                                    ivZan.setImageResource(R.mipmap.zan_1);
                                }

                                if (bean.getCommentDiscussList() != null && bean.getCommentDiscussList().size() > 0) {
                                    holder.getView(R.id.llAnswerComment).setVisibility(View.VISIBLE);
                                    holder.getView(R.id.answerNumber).setVisibility(View.VISIBLE);
                                    holder.setText(R.id.answerNumber, bean.getCommentDiscussList().size() + "回复");
                                    holder.setText(R.id.tvAnswerName, bean.getCommentDiscussList().get(0).getUsername1());
                                    holder.setText(R.id.tvAnswerContent, bean.getCommentDiscussList().get(0).getDiscussContent());
                                    holder.getView(R.id.tvCommentType).setVisibility(View.GONE);
                                } else {
                                    holder.getView(R.id.llAnswerComment).setVisibility(View.GONE);
                                    holder.getView(R.id.answerNumber).setVisibility(View.GONE);
                                }

                                holder.getView(R.id.zan).setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        if (checkIsLogin("登录后可查看更多内容")) {
                                            //点赞接口
                                            index = mBaseAdapter.getItemIndex(bean);
                                            if (TextUtils.isEmpty(bean.getLikeId())) {
                                                dealZan(bean.getId(), "1", 4);
//                                            bean.setLikeId("222");
                                            } else {
//                                            bean.setLikeId("");
//                                            mBaseAdapter.getData();
                                                dealZan(bean.getId(), "0", 4);
                                            }
                                        }
                                    }
                                });
                            }
                        }


                        @Override
                        public void onItemClick(View view, int position) {
                            if (position != 0) {
                                IndustryInfoDetailVO.InformationCommentListBean answerListBean = (IndustryInfoDetailVO.InformationCommentListBean) mBaseAdapter.getData(position);
                                if (toUserId != null && toUserId.equals(String.valueOf(answerListBean.getUserId()))) {
                                    toUserId = null;
                                    answerId = null;
                                    etComment.setHint("写评论");
                                } else {
                                    toUserId = String.valueOf(answerListBean.getUserId());
                                    answerId = answerListBean.getId();
                                    etComment.setHint("回复" + answerListBean.getUsername1());
                                }
                            }
                        }
                    });


                }
                return holder;
            }

            @Override
            public int getItemViewType(int position) {
                IndustryInfoDetailVO.InformationCommentListBean bean = (IndustryInfoDetailVO.InformationCommentListBean) mBaseAdapter.getData().get(position);
                if (bean.isHeader())
                    return 1;//头部布局
                else
                    return 2;

            }
        };
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mRecyclerView.setAdapter(mBaseAdapter);
//        mBaseAdapter.setData(new ArrayList());
    }

    private int index = -1;

    //点赞接口
    private void dealZan(String id, final String temp, final int type) {
        if (Util.isEmpty(PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID))) {
            showTost("未登录，不能点赞！请先登录", 1);
            return;
        }
        if (Util.isEmpty(id))
            return;
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("temp", temp);
        params.put("type", type);
        params.put("id", id);
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody> call = apiservice.doLike(params);
        call.enqueue(new Callback<ApiResponseBody>() {
            @Override
            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                dismissProgress();
                if (response.isSuccessful()) {
                    if (type == 4) {
                        if (index == -1)
                            return;
                        IndustryInfoDetailVO.InformationCommentListBean bean = (IndustryInfoDetailVO.InformationCommentListBean) mBaseAdapter.getData(index);
                        int num = bean.getLikeNum();
                        if (temp.equals("1")) {
                            num++;
                            bean.setLikeId("13");
                        } else {
                            num--;
                            bean.setLikeId(null);
                        }
                        bean.setLikeNum(num);
                        mBaseAdapter.update(bean, index);
                    }
                } else {
                    showTost(response.raw().message(), 0);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                dismissProgress();
                ApiException exception = ExceptionHandle.handleException(t);
                if (exception.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (exception.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(exception.getMessage(), 1);
                }
            }
        });

    }

    @Override
    public void loadData() {
//        getHead();

    }

    @Override
    public void onResume() {
        super.onResume();
        getRemarkList(mPage);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tvShare:
                Intent intent = new Intent(getActivity(), ShareActivity.class);
                intent.putExtra("type", 4);
                intent.putExtra("id", infoId);
                startActivity(intent);
                break;
            case R.id.myBack:
                getActivity().onBackPressed();
                break;
            case R.id.commit:
                if (TextUtils.isEmpty(toUserId))
                    commitComment();
                else
                    addDiscuss();
                break;
            case R.id.tv_answer:
                toUserId = null;
                answerId = null;
                etComment.setHint("写评论");
                toUserName.setText("");
                break;
            case R.id.ivCollect:
                if (isCollect) {
                    doCollection(infoId, 0);
                } else {
                    doCollection(infoId, 1);
                }
                break;
            case R.id.myToolbarRight:
                if (isFollow)// // 0取消关注 1关注
                    doFollow(0);
                else
                    doFollow(1);
                break;
        }
    }


    private IndustryInfoDetailVO mIndustrDetail;
    private int isAdd = 1; //1 增加 1  0 不增加

    private void getRemarkList(final int mPage) {
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("informationId", String.valueOf(infoId));
        params.put("page", mPage);
        params.put("isAdd", isAdd);
        params.put("userId", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        if (isAdd == 1)
            isAdd = 0;
        Call<ApiResponseBody<IndustryInfoDetailVO>> call = apiservice.selInformationDetail(params);
        call.enqueue(new Callback<ApiResponseBody<IndustryInfoDetailVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<IndustryInfoDetailVO>> call, Response<ApiResponseBody<IndustryInfoDetailVO>> response) {
                if (mRefreshRecyclerView == null) {
                    return;
                }
                mRefreshRecyclerView.endPage();

                if (response.isSuccessful()) {
                    IndustryInfoDetailVO bean = response.body().getResult();
                    if (mPage == 1) {
                        if (bean != null) {

                            IndustryInfoDetailVO.InformationCommentListBean header = new IndustryInfoDetailVO.InformationCommentListBean();
                            header.setHeader(true);
                            bean.getInformationCommentList().add(0, header);

                            mIndustrDetail = bean;
                            if (bean.getInformationDetail() == null)
                                return;
                            authorId = bean.getInformationDetail().getUserId();
                            mBaseAdapter.setData(bean.getInformationCommentList());

                            if (TextUtils.isEmpty(bean.getInformationDetail().getCollectId())) {
                                isCollect = false;
                                ivCollect.setImageResource(R.mipmap.ico_collect_xw_nu);
                            } else {
                                isCollect = true;
                                ivCollect.setImageResource(R.mipmap.ico_collect_wx);
                            }
                            if (TextUtils.isEmpty(bean.getInformationDetail().getFollowId())||
                                    authorId.equals(PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID))) {
                                isFollow = false;
                                myToolbarRight.setText("关注");
                            } else {
                                isFollow = true;
                                myToolbarRight.setText("已关注");
                            }
                            if (TextUtils.isEmpty(bean.getInformationDetail().getLikeId())) {
                                like = false;
                            } else {
                                like = true;
                            }
                            if (!Util.isEmpty(mIndustrDetail.getInformationDetail().getUserPic()))
                                ImageDisplayUtil.loadCircleHeadImage(getActivity(), userHead, mIndustrDetail.getInformationDetail().getUserPic());
                            Date date = Util.StrToDate(mIndustrDetail.getInformationDetail().getAddTime(), "yyyy.MM.dd HH:mm:ss");
                            String timeStr = Utils.getAskTime(date);
                            addTime.setText(timeStr);
                            myToolbarName.setText(mIndustrDetail.getInformationDetail().getUserName());
                            mRefreshRecyclerView.showNextMore(mPage);
                        }

                    } else {
                        if (bean == null || bean.getInformationCommentList().size() == 0) {
                            mRefreshRecyclerView.showNoMore();
                        } else {

                            mBaseAdapter.addData(BaseAdapter.AddType.LASE, bean.getInformationCommentList());
                            mIndustrDetail.setInformationCommentList(mBaseAdapter.getData());
                            mRefreshRecyclerView.showNextMore(mPage);
                        }
                    }
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<IndustryInfoDetailVO>> call, Throwable t) {
                if (mRefreshRecyclerView == null) {
                    return;
                }
                mRefreshRecyclerView.endPage();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });

    }

    //评论
    private void commitComment() {
        if (Util.isEmpty(PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID))) {
            showTost("未登录！请先登录", 1);
            return;
        }
        if (Util.isEmpty(etComment.getText().toString())) {
            showTost("请先输入评论内容", 1);
            return;
        }
        hideSoftKeyboard();
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("id", infoId);
        params.put("content", etComment.getText().toString());
        if (!Utils.noContainsEmoji(etComment.getText().toString().trim())) {
            showTost("不支持输入emoji表情", 1);
            return;
        }
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody<CommentVO>> call = apiservice.addComment(params);
        call.enqueue(new Callback<ApiResponseBody<CommentVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<CommentVO>> call, Response<ApiResponseBody<CommentVO>> response) {
                dismissProgress();
                if (response.isSuccessful()) {
//                    CommentVO bean = response.body().getResult();
//                    CommentListVO vo = new CommentListVO();
//                    vo.setAddTime(bean.getAddTime());
//                    vo.setBackInfo(bean.getBackInfo());
//                    vo.setUserName(PreferencesUtil.getString(getActivity(), PreferencesUtil.KEY_NAME));
//                    vo.setContent(bean.getContent());
//                    mBaseAdapter.addData(BaseAdapter.AddType.FIRST, vo);
//                    mRecyclerView.scrollToPosition(0);
                    etComment.setText("");
                    etComment.setHint("写评论");
                    commit.setVisibility(View.GONE);
                    mPage = 1;
                    getRemarkList(mPage);
                    if (mRecyclerView.getChildCount() > 2) {
                        mRecyclerView.scrollToPosition(3);
                    } else {
                        mRecyclerView.scrollToPosition(1);
                    }

                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<CommentVO>> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });

    }

    //回复评论
    private void addDiscuss() {
        if (Util.isEmpty(PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID))) {
            showTost("未登录！请先登录", 1);
            return;
        }
        String answer = etComment.getText().toString().trim();
        if (Util.isEmpty(answer)) {
            showTost("请输入您的评论", 1);
            return;
        }
        if (answer.length() > 500) {
            showTost("请将评论控制在500字内，当前字数：" + answer.length(), 1);
            return;
        }
        if (!Utils.noContainsEmoji(answer)) {
            showTost("不支持输入emoji表情", 1);
            return;
        }
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("commentId", answerId);
        params.put("content", answer);
        params.put("userId", PreferencesUtil.getString(getContext(), PreferencesUtil.USER_ID));
        params.put("platform", "0");
        params.put("deviceId", Utils.getDeviceId(MyApplication.getInstance()));
        params.put("page", 1);
        params.put("toUserId", toUserId);
        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody> call = apiservice.insertInfoDiscuss(params);
        call.enqueue(new Callback<ApiResponseBody>() {
            @Override
            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                dismissProgress();
                if (response.isSuccessful()) {
                    showTost("提交成功", 0);
                    commit.setVisibility(View.GONE);
                    getBaseActivity().hideSoftKeybord();
                    toUserName.setText("");
                    etComment.setText("");
                    etComment.setHint("写评论");
                    toUserId = null;
                    answerId = null;
                    getRemarkList(mPage);
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.collect, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    //收藏
    private void doCollection(String id, final int i) {
        if (checkIsLogin("登录后可体验更多内容")) {
            Apiservice apiservice = ApiUtil.getInstance().create();
            HashMap hashMap = new HashMap();
            hashMap.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
            hashMap.put("type", 0);
            hashMap.put("id", id);
            //0取消收藏 1收藏
            hashMap.put("temp", i);
            showProgress(getClass().getSimpleName());
            Call<ApiResponseBody> call = apiservice.collect(hashMap);
            call.enqueue(new Callback<ApiResponseBody>() {
                @Override
                public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                    dismissProgress();
                    if (response.isSuccessful()) {
                        isCollect = !isCollect;
                        if (isCollect) {
                            ivCollect.setImageResource(R.mipmap.ico_collect_wx);
                        } else {
                            ivCollect.setImageResource(R.mipmap.ico_collect_xw_nu);
                        }
                    } else {
                        showTost(response.raw().message(), 1);
                    }
                }

                @Override
                public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                    dismissProgress();
                    ApiException apiException = ExceptionHandle.handleException(t);
                    if (apiException.isTokenInvalid()) {
                        showUnLoginSnackbar();
                    } else if (apiException.isNetConnected()) {
                        showSetNetworkSnackbar();
                    } else {
                        showTost(apiException.getMessage(), 0);
                    }
                }
            });
        }

    }

    //关注
    private boolean isFollow;

    private void doFollow(int i) {
        if (checkIsLogin("登录后可体验更多内容")) {
            if (TextUtils.isEmpty(authorId)) {
                showTost("该作者无法被关注", 0);
                return;
            }
            if (authorId.equals(PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID))) {
                showTost("无法关注自己", 0);
                return;
            }
            Apiservice apiservice = ApiUtil.getInstance().create();
            HashMap params = new HashMap();
            params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
            //0:二手机 1:设备出租 2:设备求租 3:工程师
            params.put("type", 3);
            params.put("temp", i);
            params.put("id", authorId);
            showProgress(getClass().getSimpleName());
            Call<ApiResponseBody> call = apiservice.follow(params);
            call.enqueue(new Callback<ApiResponseBody>() {
                @Override
                public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                    dismissProgress();
                    if (response.isSuccessful()) {

                        isFollow = !isFollow;
                        if (isFollow) {
                            myToolbarRight.setText("已关注");
                        } else {
                            myToolbarRight.setText("关注");
                        }
                        mBaseAdapter.notifyDataSetChanged();
                    } else {
                        showTost(response.raw().message(), 1);
                    }
                }

                @Override
                public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                    dismissProgress();
                    ApiException apiException = ExceptionHandle.handleException(t);
                    if (apiException.isTokenInvalid()) {
                        showUnLoginSnackbar();
                    } else if (apiException.isNetConnected()) {
                        showSetNetworkSnackbar();
                    } else {
                        showTost(apiException.getMessage(), 0);
                    }
                }
            });
        }
    }


}
